<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片描述生成与对话</title>
   <style>
        /* 全局样式 */
        body {
            font-family: 'Arial', sans-serif;
            background: linear-gradient(to bottom, #fef6e4, #fde2e4);
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        /* 标题样式 */
        h1 {
            color: #ff6f61;
            text-align: center;
            font-size: 32px;
            margin-top: 20px;
        }

        h2 {
            color: #ff8fab;
            text-align: center;
            font-size: 26px;
        }

        h3 {
            color: #f8b400;
            font-size: 22px;
            margin-top: 10px;
        }

        /* 描述内容样式 */
        #output {
            margin-top: 20px;
            white-space: pre-wrap;
            font-family: 'Comic Sans MS', cursive;
            border: 3px dashed #ffb6b9;
            border-radius: 15px;
            padding: 20px;
            width: 600px;
            height: 150px;
            overflow-y: auto;
            background: #fff;
            color: #8a2be2;
            font-size: 18px;
            line-height: 1.6;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

        /* 聊天区域样式 */
        #chatSection {
            background: #ffdab9;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            margin: 20px 0 40px 0;
            width: 600px;
        }

        #chatMessages {
            width: 600px;
            height: 500px;
            border: 3px dashed #ffb6b9;
            border-radius: 15px;
            padding: 20px;
            overflow-y: auto;
            background: #fff;
            margin-bottom: 15px;
        }

        /* 聊天气泡样式 */
        .user-message {
            text-align: right;
            background: #ffd6e7;
            border-radius: 20px 20px 0 20px;
            padding: 12px 18px;
            margin: 10px;
            color: #ff4081;
            font-size: 16px;
            max-width: 80%;
            float: right;
            clear: both;
            box-shadow: 2px 2px 8px rgba(0,0,0,0.1);
        }

        .ai-message {
            text-align: left;
            background: #e0f7fa;
            border-radius: 20px 20px 20px 0;
            padding: 12px 18px;
            margin: 10px;
            color: #00bcd4;
            font-size: 16px;
            max-width: 80%;
            float: left;
            clear: both;
            box-shadow: 2px 2px 8px rgba(0,0,0,0.1);
            display: flex;
            align-items: flex-start;
        }

        .ai-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin-right: 10px;
            object-fit: cover;
        }

        .user-message strong {
            color: #e91e63;
            font-weight: bold;
            font-size: 17px;
        }

        .ai-message strong {
            color: #00838f;
            font-weight: bold;
            font-size: 17px;
        }

        #chatMessages::after {
            content: '';
            display: table;
            clear: both;
        }

        /* 输入框样式 */
        #chatInput {
            width: 75%;
            padding: 12px;
            border: 2px solid #ffb6b9;
            border-radius: 25px;
            outline: none;
            font-size: 16px;
            transition: all 0.3s ease;
            margin-right: 10px;
        }

        #chatInput:focus {
            border-color: #ff4081;
            box-shadow: 0 0 10px rgba(255,64,129,0.2);
        }

        #chatSection button {
            background: #ff4081;
            color: #fff;
            border: none;
            padding: 12px 25px;
            border-radius: 25px;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s ease;
        }

        #chatSection button:hover {
            background: #e91e63;
            transform: scale(1.05);
        }
    </style>
</head>
<body>
    <h1>✨ Image Description Generation and Conversation ✨</h1>

    <!-- 图片上传部分 -->
    <form id="uploadForm">
        <input type="file" id="imageInput" accept="image/png, image/jpeg, image/gif">
        <button type="button" onclick="uploadImage()">📤 上传并生成描述</button>
    </form>
    <h3>📝 Description Content:</h3>
    <div id="output"></div>

    <hr style="width: 80%; margin: 20px 0;">

    <!-- 对话部分 -->
    <h2>💬 Conversation Area</h2>
    <div id="chatSection">
        <div id="chatMessages"></div>
        <input type="text" id="chatInput" placeholder="输入你的问题...">
        <button onclick="sendMessage()">🚀 发送</button>
    </div>

    <script>
        let aiAvatar = null;

        // =============================
        // 图片上传与描述生成（流式）
        // =============================
        function uploadImage() {
            const fileInput = document.getElementById('imageInput');
            const outputDiv = document.getElementById('output');
            outputDiv.innerText = ''; // 清空上次的内容

            if (!fileInput.files.length) {
                alert('请选择一张图片上传！');
                return;
            }

            const file = fileInput.files[0];

            // 创建一个小头像
            const reader = new FileReader();
            reader.onload = function(e) {
                aiAvatar = e.target.result;
            }
            reader.readAsDataURL(file);

            const formData = new FormData();
            formData.append('image', file);

            fetch('/upload', {
                method: 'POST',
                body: formData
            }).then(response => {
                if (!response.body) {
                    throw new Error('服务器未返回流式数据');
                }
                const reader = response.body.getReader();
                const decoder = new TextDecoder();

                function readStream() {
                    reader.read().then(({ done, value }) => {
                        if (done) return;
                        const chunk = decoder.decode(value, { stream: true });
                        chunk.split('\n').forEach(line => {
                            if (line.startsWith('data:')) {
                                const content = line.replace('data: ', '').trim();
                                if (content !== '[DONE]') outputDiv.innerText += content;
                            }
                        });
                        readStream();
                    });
                }
                readStream();
            });
        }

        // =============================
        // 聊天对话功能
        // =============================
        function sendMessage() {
            const chatInput = document.getElementById('chatInput');
            const chatMessages = document.getElementById('chatMessages');
            const userMessage = chatInput.value.trim();

            if (!userMessage) {
                alert('请输入内容再发送！');
                return;
            }

            chatMessages.innerHTML += `<div class="user-message"><strong>你:</strong> ${userMessage}</div>`;
            chatInput.value = '';

            const messageDiv = document.createElement('div');
            messageDiv.className = 'ai-message';

            // 添加AI头像
            let avatarHtml = '';
            if (aiAvatar) {
                avatarHtml = `<img src="${aiAvatar}" class="ai-avatar" alt="AI">`;
            }

            messageDiv.innerHTML = `${avatarHtml}<div><strong>AI:</strong> </div>`;
            chatMessages.appendChild(messageDiv);

            // 自动滚动到底部
            chatMessages.scrollTop = chatMessages.scrollHeight;

            fetch('/chat', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ message: userMessage })
            }).then(response => {
                const reader = response.body.getReader();
                const decoder = new TextDecoder();

                function readStream() {
                    reader.read().then(({ done, value }) => {
                        if (done) return;
                        const chunk = decoder.decode(value, { stream: true });
                        chunk.split('\n').forEach(line => {
                            if (line.startsWith('data:')) {
                                const content = line.replace('data: ', '').trim();
                                if (content !== '[DONE]') {
                                    messageDiv.querySelector('div').innerHTML += content;
                                    chatMessages.scrollTop = chatMessages.scrollHeight;
                                }
                            }
                        });
                        readStream();
                    });
                }
                readStream();
            });
        }

        // 添加回车发送功能
        document.addEventListener('DOMContentLoaded', function() {
            const chatInput = document.getElementById('chatInput');
            chatInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault(); // 阻止默认的换行行为
                    sendMessage();
                }
            });
        });
    </script>
</body>
</html>
